//
//  API_Codable_primary_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/21.
//

import UIKit

class API_Codable_primary_DemoVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        test_JSONToModel()
        
        test_ModelToJSON()
    }

}

extension API_Codable_primary_DemoVC {
    struct Person: Codable {
        var name: String
        var age: Int
        var isEmployed: Bool
        

    }
    
    private func test_JSONToModel() {
        let jsonString =
        """
        {
            "name": "小明",
            "age": 12,
            "isEmployed": true
        }
        """
        guard let data = jsonString.data(using: .utf8) else { return }

        /// 方式一
        do {
            let xiaoMing = try JSONDecoder().decode(Person.self, from: data)
            debugPrint("JSONToModel (try catch) - is: \(xiaoMing.name), \(xiaoMing.age), \(xiaoMing.isEmployed)")
        } catch {
            debugPrint("JSONToModel (try catch) - catch error is: \(error)")
        }

        /// 方式二
        if let xm = try? JSONDecoder().decode(Person.self, from: data) {
            debugPrint("JSONToModel (try?) - is: \(xm.name), \(xm.age), \(xm.isEmployed)")
        } else {
            debugPrint("JSONToModel (try?) - 解析失败啦啦啦")
        }

    }

    private func test_ModelToJSON() {
        let stu = Person(name: "xiaoming", age: 18, isEmployed: true)

        /// 方式一
        do {
            let data = try JSONEncoder().encode(stu)
            let jsonString = String(data: data, encoding: .utf8)
            debugPrint("ModelToJSON（do catch）jsonString is： \(String(describing: jsonString))")
        } catch {
            debugPrint("ModelToJSON（do catch）catch error is: \(error)")
        }

        /// 方式二
        if let data = try? JSONEncoder().encode(stu) {
            let jsonString = String(data: data, encoding: .utf8)
            debugPrint("ModelToJSON（try?）jsonString is： \(String(describing: jsonString))")
        } else {
            debugPrint("ModelToJSON（try?）- 解析失败啦啦啦")
        }
    }
}
